import { ReactElement, useEffect, useState } from 'react'
import { Moment } from 'moment'
import { RoomSchema, BookedSchema } from '@src/components/schema/room';
import { getRoomListRequest, getBookListRequest } from './ajax'
import { message, Space } from 'antd';
import { awaitWrap } from '@src/assets/js/tool';
import classNames from 'classnames';
import style from './index.module.less'
import moment from 'moment';

async function initRooms (setRooms: (v: RoomSchema[]) => void) {
  const [e, d] = await awaitWrap(getRoomListRequest())
  if (e === null && d !== null) {
    setRooms(d)
  }
}

async function initBooked (day: string, setList: (v: BookedSchema[]) => void) {
  const h = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getBookListRequest(day))
  h()
  if (e === null && d !== null) {
    setList(d)
  }
}

interface Props {
  value?: string
  onChange?: (v: string) => void
  date: Moment | null
  visible: boolean
}

function Main ({ value, onChange = () => {}, date, visible }: Props): ReactElement {
  const [rooms, setRooms] = useState<RoomSchema[]>([])
  const [list, setList] = useState<BookedSchema[]>([])
  useEffect(() => {
    initRooms(setRooms)
  }, [])
  useEffect(() => {
    if (date) {
      initBooked(date.format('YYYY-MM-DD'), setList)
    } else {
      setList([])
    }
  }, [date, visible])
  return (
    <Space size={[24, 24]} wrap>
      {
        rooms.map((li, i) => {
          const l = list.filter(o => o.hearingroomid === li.id).sort((a, b) => a.begin_datetime - b.begin_datetime)
          return (
            <div key={i} className={classNames(style.block, { [style.active]: value === li.id })} onClick={() => {
              onChange(li.id)
            }}>
              <div className={style['block-title']}>{li.name}</div>
              {l.length === 0 && <div className={style.placeholder}>全天可预约</div>}
              <Space size={[16, 8]} wrap>
                {l.map((o, j) => {
                  const b = moment(o.begin_datetime * 1000).format('HH:mm')
                  const e = moment(o.end_datetime * 1000).format('HH:mm')
                  return <div key={j} className={style.date}>{b} ~ {e}</div>
                })}
              </Space>
            </div>
          )
        })
      }
    </Space>
  )
}

export default Main
